package my.sample.ha.cluster;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import org.jgroups.Address;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.View;

public class FileLogger extends ReceiverAdapter {

    JChannel channel;
    String user_name=System.getProperty("user.name", "n/a");
    int nodePort = 0;
    static String id = "";

    private void start() throws Exception {
        channel=new JChannel();
//        channel.setReceiver(this);
        channel.connect("FileLoggerCluster");
//       	nodePort = Integer.parseInt(channel.getAddress().toString().split("-")[2]);
        System.out.println("Channel getAddress : " + channel.getAddress().toString());
//       	System.out.println("Current Node Port : " + nodePort);
/*        eventLoop();
        channel.close();*/
        
        eventLoop();
    }
	
	public static void main(String[] args) throws Exception {
		id = args[0];
		new FileLogger().start();
	}
	
	public void writeToFile() {
		
		try {
			File file = new File("/tmp/file.txt");
			if (!file.exists()) {
				file.createNewFile();
			}
			
			FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(id + ": " + new Date().toString() + "\n");
			bw.close();
			Thread.sleep(1000);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
    private void eventLoop() throws InterruptedException {
        while(true) {
        	Thread.sleep(1000);
        	writeToFile();
        }
    }

    public void viewAccepted(View new_view) {
//        System.out.println("** view: " + new_view);
//        System.out.println(new_view.getMembers());
//    	System.out.println("View - vid : " + new_view.getVid() + " - viewId : " + new_view.getViewId());

    	if ( Integer.parseInt(new_view.getMembers().get(0).toString().split("-")[2])== nodePort) {
    		while (true) {
    			writeToFile();
    		}
    	}
/*        for ( Address member : new_view.getMembers()) {
        	int portNumber = Integer.parseInt(member.toString().split("-")[2]);
//        	System.out.println("Member - ipaddr : " + member.IP_ADDR + " - uuid addr" + member.UUID_ADDR );
        	System.out.println("port number : " + portNumber);
        }*/
    }

    public void receive(Message msg) {
        System.out.println(msg.getSrc() + ": " + msg.getObject());
    }

}
